﻿using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

namespace BToolkit
{
    public class PanelSharePhoto : MonoBehaviour
    {
        public BButton btnClose;
        public RawImage photo;
        public BButton btnFriend, btnMoment;
        public Texture2D waterMarking;
        public AudioClip sound;

        public static void Show(Texture2D texture)
        {
            PanelSharePhoto panelSharePhoto = Instantiate(Resources.Load<PanelSharePhoto>("PanelSharePhoto"));
            panelSharePhoto.transform.SetParent(FindObjectOfType<Canvas>().transform, false);
            panelSharePhoto.SetContent(texture);
        }

        void Awake()
        {
            btnClose.AddClick(() =>
            {
                Destroy(gameObject);
            });
            btnFriend.AddClick(ShareToFriend);
            btnMoment.AddClick(ShareToMoment);
            photo.transform.parent.localScale = Vector3.one;
            (photo.transform.parent as RectTransform).anchoredPosition = Vector3.zero;
            photo.transform.parent.eulerAngles = Vector3.zero;
        }

        void SetContent(Texture2D texture)
        {
            //添加水印
            if (waterMarking)
            {
                texture = TextureUtils.AddWaterMarking(texture, waterMarking);
            }
            photo.enabled = false;
            SavePhotoToAlbum.Save(texture.EncodeToJPG(), TimeUtils.GetCurrTimeStamp() + ".jpg");
            photo.enabled = true;
            photo.texture = texture;
            StartAnim();
        }

        void StartAnim()
        {
            SoundPlayer.PlayAndDestroy(0, sound);
            float time = 0.5f;
            photo.transform.parent.DOScale(Vector3.one * 0.8f, time).SetEase(Ease.OutExpo);
            photo.transform.parent.DOLocalMove(new Vector2(0, 38), time).SetEase(Ease.OutExpo);
            photo.transform.parent.DORotate(new Vector3(0, 0, Random.Range(0, 2) == 0 ? 3 : -3), time).SetEase(Ease.OutExpo);
        }

        void ShareToFriend()
        {
            string tempSavePath = SaveForShare();
            WeiXinShare.Instance.ShareImageToFriend("魔镜", "魔镜AR", tempSavePath);
        }

        void ShareToMoment()
        {
            string tempSavePath = SaveForShare();
            WeiXinShare.Instance.ShareImageToMoments("魔镜", "魔镜AR", tempSavePath);
        }

        string SaveForShare()
        {
            string tempSavePath = Application.persistentDataPath + "/share.jpg";
            StorageUtils.SaveBytesToFile((photo.texture as Texture2D).EncodeToJPG(), tempSavePath);
            return tempSavePath;
        }
    }
}